import React, { useState } from 'react'
import { X, Download, FileText, Code, Image } from 'lucide-react'

interface ExportDialogProps {
  isOpen: boolean
  onClose: () => void
  content: string
  fileName: string
}

const ExportDialog: React.FC<ExportDialogProps> = ({
  isOpen,
  onClose,
  content,
  fileName
}) => {
  const [format, setFormat] = useState<'pdf' | 'html' | 'png' | 'md'>('pdf')
  const [isExporting, setIsExporting] = useState(false)

  const handleExport = async () => {
    setIsExporting(true)
    try {
      switch (format) {
        case 'pdf':
          await exportToPDF()
          break
        case 'html':
          await exportToHTML()
          break
        case 'png':
          await exportToPNG()
          break
        case 'md':
          await exportToMarkdown()
          break
      }
    } catch (error) {
      console.error('Export failed:', error)
    } finally {
      setIsExporting(false)
      onClose()
    }
  }

  const exportToPDF = async () => {
    // Placeholder for PDF export functionality
    // In a real implementation, you would use libraries like puppeteer or electron-pdf
    console.log('Exporting to PDF...')
    const blob = new Blob([content], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${fileName}.pdf`
    a.click()
    URL.revokeObjectURL(url)
  }

  const exportToHTML = async () => {
    // Simple markdown to HTML conversion
    const htmlContent = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <title>${fileName}</title>
        <style>
          body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 800px; margin: 0 auto; padding: 40px 20px; line-height: 1.6; }
          h1, h2, h3 { color: #333; margin-top: 1.5em; margin-bottom: 0.5em; }
          h1 { border-bottom: 2px solid #eee; padding-bottom: 10px; }
          h2 { border-bottom: 1px solid #eee; padding-bottom: 8px; }
          p { margin: 1em 0; }
          code { background: #f4f4f4; padding: 2px 4px; border-radius: 3px; font-family: 'Monaco', 'Menlo', monospace; }
          pre { background: #f4f4f4; padding: 10px; border-radius: 5px; overflow-x: auto; }
          blockquote { border-left: 4px solid #ddd; margin: 0; padding-left: 20px; color: #666; }
          table { border-collapse: collapse; width: 100%; margin: 1em 0; }
          th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
          th { background: #f5f5f5; }
        </style>
      </head>
      <body>
        ${markdownToHTML(content)}
      </body>
      </html>
    `

    const blob = new Blob([htmlContent], { type: 'text/html' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${fileName}.html`
    a.click()
    URL.revokeObjectURL(url)
  }

  const exportToPNG = async () => {
    // Placeholder for PNG export
    // In a real implementation, you would use html2canvas or similar
    console.log('PNG export not yet implemented')
  }

  const exportToMarkdown = async () => {
    const blob = new Blob([content], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${fileName}.md`
    a.click()
    URL.revokeObjectURL(url)
  }

  // Simple markdown to HTML converter
  const markdownToHTML = (markdown: string): string => {
    return markdown
      .replace(/^### (.*$)/gim, '<h3>$1</h3>')
      .replace(/^## (.*$)/gim, '<h2>$1</h2>')
      .replace(/^# (.*$)/gim, '<h1>$1</h1>')
      .replace(/\*\*(.*)\*\*/gim, '<strong>$1</strong>')
      .replace(/\*(.*)\*/gim, '<em>$1</em>')
      .replace(/`([^`]*)`/gim, '<code>$1</code>')
      .replace(/```([^`]*)```/gims, '<pre><code>$1</code></pre>')
      .replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>')
      .replace(/\n\n/gim, '</p><p>')
      .replace(/\n/gim, '<br>')
      .replace(/^/, '<p>')
      .replace(/$/, '</p>')
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">导出文档</h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500 dark:text-gray-400" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6">
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                选择导出格式
              </label>
              <div className="grid grid-cols-2 gap-3">
                <button
                  onClick={() => setFormat('pdf')}
                  className={`p-4 border rounded-lg flex flex-col items-center gap-2 transition-colors ${
                    format === 'pdf'
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
                  }`}
                >
                  <FileText className="w-6 h-6 text-red-500" />
                  <span className="text-sm font-medium">PDF</span>
                </button>

                <button
                  onClick={() => setFormat('html')}
                  className={`p-4 border rounded-lg flex flex-col items-center gap-2 transition-colors ${
                    format === 'html'
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
                  }`}
                >
                  <Code className="w-6 h-6 text-blue-500" />
                  <span className="text-sm font-medium">HTML</span>
                </button>

                <button
                  onClick={() => setFormat('png')}
                  className={`p-4 border rounded-lg flex flex-col items-center gap-2 transition-colors ${
                    format === 'png'
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
                  }`}
                >
                  <Image className="w-6 h-6 text-green-500" />
                  <span className="text-sm font-medium">PNG</span>
                </button>

                <button
                  onClick={() => setFormat('md')}
                  className={`p-4 border rounded-lg flex flex-col items-center gap-2 transition-colors ${
                    format === 'md'
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
                  }`}
                >
                  <FileText className="w-6 h-6 text-gray-500" />
                  <span className="text-sm font-medium">Markdown</span>
                </button>
              </div>
            </div>

            <div className="text-sm text-gray-600 dark:text-gray-400">
              <p><strong>文件名:</strong> {fileName}.{format}</p>
              <p className="mt-1">
                {format === 'pdf' && '适用于打印和分享的 PDF 文档'}
                {format === 'html' && '可在浏览器中打开的 HTML 网页'}
                {format === 'png' && '适用于社交媒体分享的图片'}
                {format === 'md' && '原始 Markdown 文件'}
              </p>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleExport}
            disabled={isExporting}
            className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
          >
            <Download className="w-4 h-4" />
            {isExporting ? '导出中...' : '导出'}
          </button>
        </div>
      </div>
    </div>
  )
}

export default ExportDialog